﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mimoza.Plugins.DisplaySettings
{
    public class C36SX_CE6_ExecutePlugin : BaseExecutePlugin
    {
        #region BaseExecutePlugin Members

        public override string Id
        {
            get { return this.ToString(); }
        }

        public override bool Add(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            return Apply(policy, data);
        }

        public override bool Remove(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            return false;
        }

        public override bool Update(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            return Apply(policy, data);
        }

        #endregion

        bool Apply(Mimoza.ObjectLayer.Policy policy, DisplayResolution data)
        {
            object modeNum = GetModeNumber(data);

            Common.Instrumental.Registry registry = new Mimoza.Common.Instrumental.Registry("Drivers\\Display");

            registry.CheckAndRewrite("ModeNumber", modeNum);

            return registry.IsModified;
        }

        string GetSettingsString(DisplayResolution data)
        {
            return data.Width.ToString() + "x" + data.Height.ToString() + "x" + data.ColorDepthAsInt.ToString() + "x" +
                data.Freq.ToString();
        }

        int GetModeNumber(DisplayResolution data)
        {
            string resourceStr = Resource.C36SXData;

            string settingStr = GetSettingsString(data);
            int foundIndex = resourceStr.IndexOf(settingStr);
            if (foundIndex < 0)
            {
                Common.Logger.Log.Error("Mimoza.Plugins.DisplaySettings.C36SX_CE6_ExecutePlugin.GetModeNumber string not found settingStr - '{0}'",
                    settingStr);
                throw new System.ArgumentException();
            }

            int startNumberPos = resourceStr.LastIndexOf(';', foundIndex);
            string numString = resourceStr.Substring(startNumberPos + 2,
                resourceStr.IndexOf(':', startNumberPos) - startNumberPos - 2);

            Common.Logger.Log.Trace("Mimoza.Plugins.DisplaySettings.C36SX_CE6_ExecutePlugin.GetModeNumber numString - '{0}'",
                    numString);

            int number = Convert.ToInt32(numString, 16);
            return number;
        }
    }
}
